package com.kikidao.app.dao;

import com.container.app.annotations.DAOComponent;
import com.container.app.annotations.Inject;
import com.container.app.annotations.InstanceTag;
import com.datalayer.orm.ORM;
import com.kikidao.app.exceptions.DAOUncheckedException;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * User: Georgiana.Scarlat
 * Date: 7/23/12
 * Time: 4:18 PM
 */

@DAOComponent
public class MyORMDAOUtils extends DAOUtils {

    private ORM myORM;
    private DAOProperty daoProperty;


    public MyORMDAOUtils() {
    }

    @SuppressWarnings("UnusedDeclaration")
    @Inject
    public void setDaoProperty(@InstanceTag("property") DAOProperty daoProperty) throws DAOUncheckedException {
        this.daoProperty = daoProperty;
        try {
            Class.forName(daoProperty.getProperty("driver", true));
        } catch (ClassNotFoundException e) {
            throw new DAOUncheckedException("Invalid driver in property file. ");
        }
    }

    @SuppressWarnings("UnusedDeclaration")
    @Inject
    public void setMyORM(ORM myORM) {
        this.myORM = myORM;
    }


    @Override
    public Connection getConnection() throws DAOUncheckedException {
        String url, username, password;
        Connection connection;

        url = daoProperty.getProperty("url", true);
        username = daoProperty.getProperty("user", true);
        password = daoProperty.getProperty("password", true);

        try {

            connection = myORM.initConnection(url, username, password);
            return connection;

        } catch (IllegalArgumentException e) {
            throw new DAOUncheckedException("Invalid properties in property file. ");
        }

    }

    @Override
    public void endConnection() throws DAOUncheckedException {
        try {
            myORM.closeConnection();
        } catch (SQLException e) {
            throw new DAOUncheckedException("Can't close the connection, ");
        }
    }


}
